<template>
    <div class="home-wrapper" v-loading="fullScreenLoading">
        <project-menu :detail="projectDetail" :pid="projectId"></project-menu>
        <div class="filters-wrapper" v-show="show1">
            <div class="title total_title">{{title}}</div>
            <el-row type="flex" justify="start">
                <div class="newgroup_warp">
                    <el-form :model="newgroup" ref="newgroup" :rules="newgroupRules" label-width="120px">
                        <el-form-item label="推广目的：" style="width: auto;" prop="landing_type">
                            <el-radio-group v-model="newgroup.landing_type">
                                <el-radio-button :disabled="item.disabled" v-for="item in landing_types" :key="item.id"
                                    :label="item.id">
                                    {{item.name}}</el-radio-button>
                                <!-- <el-radio-button label="2">销售线索收集</el-radio-button>
                                <el-radio-button label="3">抖音号推广</el-radio-button>
                                <el-radio-button label="4">门店推广</el-radio-button>
                                <el-radio-button label="5">电商店铺推广</el-radio-button>
                                <el-radio-button label="6">头条文章推广</el-radio-button> -->
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item label="广告组名称：" prop="campaign_name">
                            <el-input v-model="newgroup.campaign_name" style="width: 280px;">
                            </el-input>
                        </el-form-item>
                        <el-form-item label="广告组预算：" prop="budget">
                            <el-input v-model="newgroup.budget" style="width: 280px;">
                            </el-input>
                        </el-form-item>
                        <el-form-item>
                            <el-button @click="back">取消</el-button>
                            <el-button type="primary" :loading="loading" @click="change">保存并新建计划</el-button>
                        </el-form-item>
                    </el-form>
                </div>
            </el-row>
        </div>
        <div class="" v-show="show2">
            <el-row type="flex" justify="start">
                <div class="newgroup_warp">
                    <el-form :model="newplan" ref="newplan" :rules="newplanRules" label-width="120px">
                        <div class="filters-wrapper">
                            <div class="title total_title">{{titlePlan}}</div>
                            <el-form-item label="定向包：" required prop="id_direct_packet">
                                <el-select v-model="newplan.id_direct_packet" placeholder="请选择">
                                    <el-option v-for="item in directionaldata" :key="item.id" :label="item.name"
                                        :value="item.id"></el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item label="自定义人群：">
                                <ul class="tab-tilte">
                                    <li @click="crowdCur=1" :class="{active:crowdCur==1}">不限</li>
                                    <li @click="crowdCur=2" :class="{active:crowdCur==2}">自定义人群</li>
                                </ul>
                                <div class="tab-content">
                                    <div v-show="crowdCur==1"></div>
                                    <div v-show="crowdCur==2">
                                        <el-form-item label="定向逻辑：" style="margin:20px 0 0 -120px;">
                                            <ul class="tab-tilte">
                                                <li @click="changeLogic(1)" :class="{active:prologicCur==1}">定向</li>
                                                <li @click="changeLogic(2)" :class="{active:prologicCur==2}">排除</li>
                                                <li @click="changeLogic(3)" :class="{active:prologicCur==3}">同时定向排除</li>
                                            </ul>
                                            <div class="tab-content">
                                                <div v-show="prologicCur==1" style="margin-top: 15px;">
                                                    <CrowdPicker v-model="tags" :advertiser_id="advertiser_id"
                                                        title="定向"></CrowdPicker>
                                                </div>
                                                <div v-show="prologicCur==2" style="margin-top: 15px;">
                                                    <CrowdPicker v-model="tags" :advertiser_id="advertiser_id"
                                                        title="排除"></CrowdPicker>
                                                </div>
                                                <div v-show="prologicCur==3" style="margin-top: 15px;">
                                                    <CrowdPicker v-model="tags" :advertiser_id="advertiser_id"
                                                        :showtab="true" title="定向+排除"></CrowdPicker>
                                                </div>
                                            </div>
                                        </el-form-item>
                                    </div>
                                </div>
                            </el-form-item>
                            <el-form-item label="行为兴趣：">
                                <ul class="tab-tilte">
                                    <li @click="newplan.interest_action_mode='UNLIMITED'"
                                        :class="{active:newplan.interest_action_mode=='UNLIMITED'}">不限</li>
                                    <li @click="newplan.interest_action_mode='RECOMMEND'"
                                        :class="{active:newplan.interest_action_mode=='RECOMMEND'}">系统推荐</li>
                                    <li @click="newplan.interest_action_mode='CUSTOM'"
                                        :class="{active:newplan.interest_action_mode=='CUSTOM'}">自定义</li>
                                </ul>
                                <div class="tab-content" style="margin-top: 15px;">
                                    <div v-show="newplan.interest_action_mode=='UNLIMITED'"></div>
                                    <div v-show="newplan.interest_action_mode=='RECOMMEND'"></div>
                                    <div v-show="newplan.interest_action_mode=='CUSTOM'">
                                        <el-form-item label="行为：" style="margin-left: -120px;">
                                            <FeaturePicker v-model="actionObj"></FeaturePicker>
                                        </el-form-item>
                                        <!-- 分割线 -->
                                        <el-form-item label="兴趣：" style="margin:20px 0 0 -120px;">
                                            <FeaturePicker :hideTop="true" v-model="interestObj"></FeaturePicker>
                                        </el-form-item>
                                    </div>
                                </div>
                            </el-form-item>
                        </div>
                        <div class="filters-wrapper">
                            <div class="title total_title">投放目标</div>
                            <el-form-item label="投放目标：" required>
                                <el-radio-group v-model="newplan.PutTarget">
                                    <el-radio-button label="1">转化量</el-radio-button>
                                    <el-radio-button disabled label="2">点击量</el-radio-button>
                                    <el-radio-button disabled label="3">展示量</el-radio-button>
                                </el-radio-group>
                            </el-form-item>
                            <el-form-item label="投放内容：" required>
                                <el-radio-group v-model="newplan.PutContent">
                                    <el-radio-button label="1">落地页</el-radio-button>
                                    <el-radio-button disabled label="2">小程序</el-radio-button>
                                </el-radio-group>
                            </el-form-item>
                            <el-form-item label="落地页链接：" required prop="external_url">
                                <el-input placeholder="请输入链接，可使用橙子建站提供的链接或第三方链接" v-model="newplan.external_url"
                                    class="input-with-select" style="width: 480px;">
                                    <el-button slot="append" type="primary" @click="landdchange()">使用已有</el-button>
                                </el-input>
                                <el-row type="flex" class="url-info-wrapper" v-show="newplan.urlinfo.id > 0">
                                    <i class="el-icon-caret-top"></i>
                                    <div class="url-info-img">
                                        <img :src="newplan.urlinfo.thumbnail" alt="">
                                    </div>
                                    <div class="url-info-link">
                                        <a class="info-title" href="#">
                                            {{newplan.urlinfo.name}}
                                        </a>
                                        <div class="info-desc">ID：{{newplan.urlinfo.id}}</div>
                                    </div>
                                </el-row>
                            </el-form-item>
                            <el-form-item label="创意转化组件：">
                                <el-button disabled type="primary">点击配置</el-button>
                            </el-form-item>
                            <el-form-item label="转换目标：" required prop="convert_id">
                                <el-row class="has-content-container" type="flex" align="middle"
                                    v-if="newplan.convert_id != ''">
                                    <span class="has-select">已选择：</span>
                                    <span class="has-action-names">{{newplan.convert_name}}</span>
                                    <el-button type="text" @click="targetchange()">更改</el-button>
                                </el-row>
                                <el-button v-if="newplan.convert_id == ''" type="primary" @click="targetchange()">选择转化目标
                                </el-button>
                            </el-form-item>
                            <el-form-item label="直达链接：" required>
                                <el-radio-group v-model="newplan.directLink">
                                    <el-radio-button label="1">不启用</el-radio-button>
                                    <el-radio-button disabled label="2">启用</el-radio-button>
                                </el-radio-group>
                            </el-form-item>
                        </div>
                        <div class="filters-wrapper">
                            <div class="title total_title">广告创意</div>
                            <el-form-item label="行动号召：" required prop="button_text">
                                <el-select size="small" v-model="newplan.button_text" placeholder="请选择">
                                    <el-option v-for="(item, index) in button_text" :key="index" :label="item"
                                        :value="item"></el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item label="创意包：" required prop="id_creative">
                                <el-select v-model="newplan.id_creative" multiple collapse-tags placeholder="请选择"
                                    size="small">
                                    <el-option v-for="(item, index) in creatives" :key="index"
                                        :label="item.creative_name" :value="item.id"></el-option>
                                    <!-- <el-option label="创意包：2" value="beijing"></el-option> -->
                                </el-select>
                                <span style="color: #999;padding-left: 10px;">(可多选)</span>
                            </el-form-item>
                            <el-form-item label="程序化创意：" required prop="media_nums">
                                <el-row type="flex" align="middle">
                                    <el-input size="small" v-model.number="newplan.media_nums" placeholder="素材数量"
                                        style="width: 90px;">
                                    </el-input>
                                    <i class="el-icon-close" style="margin:0 10px"></i>
                                    <el-input size="small" v-model.number="newplan.title_nums" placeholder="标题数量"
                                        style="width: 90px;">
                                    </el-input>
                                </el-row>
                            </el-form-item>
                            <el-form-item label="创意标题：">
                                <el-row type="flex" align="middle">
                                    <el-button type="primary" @click="addNewTitle">创建标题</el-button>
                                </el-row>
                                <el-row v-for="(title, index) in newplan.new_title" :key="index" type="flex" style="line-height: 1.5;">
                                    <el-col style="margin-top: 10px;width: 550px;">
                                        <el-row type="flex" align="middle">
                                            <el-input type="text" placeholder="请输入标题" v-model="title.title"
                                                ref="new_title" maxlength="30" show-word-limit />
                                            <el-button @click="deleteWord(item, index)" style="margin-left: 5px;border: none;" icon="el-icon-delete"
                                                circle></el-button>
                                        </el-row>
                                        <el-row style="width: 410px;" type="flex" align="middle" justify="start">
                                            <el-col style="width: 132px;color: #999;">插入动态词包：</el-col>
                                            <el-col>
                                              <template v-for="(item, idx) in creativeword.slice(0, 4)">
                                                <el-button type="text" @click="insertWord(item, index)" :key="idx">+{{item.name}}</el-button>
                                              </template>
                                                <el-button class="fr" @click="Cytitlechange(index)" type="text">更多</el-button>
                                            </el-col>
                                        </el-row>
                                    </el-col>
                                </el-row>
                                <!--
                                <el-row type="flex" style="line-height: 1.5;">
                                    <el-col style="margin-top: 10px;width: 450px;">
                                        <el-row type="flex" align="middle">
                                            <el-input type="text" placeholder="请输入标题" v-model="newplan.cyTitle"
                                                maxlength="30" show-word-limit />
                                            <el-button style="margin-left: 5px;border: none;" icon="el-icon-delete"
                                                circle></el-button>
                                        </el-row>
                                        <el-row style="width: 410px;" type="flex" align="middle" justify="start">
                                            <el-col style="width: 132px;color: #999;">插入动态词包：</el-col>
                                            <el-col>
                                                <el-button type="text">+地点</el-button>
                                                <el-button type="text">+日期</el-button>
                                                <el-button type="text">+星期</el-button>
                                                <el-button type="text">+年龄</el-button>
                                                <el-button class="fr" @click="Cytitlechange()" type="text">更多</el-button>
                                            </el-col>
                                        </el-row>
                                    </el-col>
                                </el-row>
                                -->
                            </el-form-item>
                        </div>
                        <div class="filters-wrapper" style="margin-bottom: 8px;">
                            <el-form-item style="margin-bottom: 0;">
                                <el-row type="flex" justify="end">
                                    <el-button @click="back">取消</el-button>
                                    <el-button @click="savePlan" :loading="loading" type="primary">保存广告计划</el-button>
                                </el-row>
                            </el-form-item>
                        </div>
                        <!-- 分割线 -->
                        <LandingPicker :landshow.sync="landshow" :advertiser_id="advertiser_id" @urlshow="urlchangs">
                        </LandingPicker>
                        <!-- 分割线 -->
                        <TargetPicker :targetshow.sync="targetshow" :advertiser_id="advertiser_id"
                            :url="newplan.external_url" v-model="cpa_bid"></TargetPicker>
                        <!-- 分割线 -->
                        <CytitlePicker :Cytitleshow.sync="Cytitleshow" @select="insertWord" :creativeword="creativeword"></CytitlePicker>
                    </el-form>
                </div>
            </el-row>
        </div>
    </div>
</template>
<script>
    import {
        landing_types,
        parseObject
    } from "@/settings"
    import FeaturePicker from '@/views/components/FeaturePicker'
    import CrowdPicker from '@/views/components/CrowdPicker'
    import LandingPicker from '@/views/components/LandingPicker'
    import TargetPicker from '@/views/components/TargetPicker'
    import CytitlePicker from '@/views/components/CytitlePicker'

    export default {
        components: {
            FeaturePicker,
            CrowdPicker,
            LandingPicker,
            TargetPicker,
            CytitlePicker,
        },
        data() {
            var validateNumber = (rule, value, callback) => {
                /*eslint no-useless-escape: "error"*/
                var myreg = /^\d{0,10}$/
                if (value != '' && !myreg.test(value)) {
                    callback(new Error('请输入数字'))
                }
                callback()
            }
            var validateMedia = (rule, value, callback) => {
                /*eslint no-useless-escape: "error"*/
                if (this.newplan.title_nums == '') {
                    callback(new Error('请输入标题数量'))
                    return
                }
                var myreg = /^\d{0,10}$/
                if (!myreg.test(value) || !myreg.test(this.newplan.title_nums)) {
                    callback(new Error('请输入数字'))
                    return
                }
                callback()
            }
            return {
                fullScreenLoading: true,
                loading: false,
                projectId: 0,
                // accountId: 0,
                advertiser_id: 0,
                landing_types: [],
                directionaldata: [],
                title: '新建广告组',
                titlePlan: '新建广告计划',
                projectDetail: {},
                show1: true,
                show2: false,
                // convert_name:'',
                creativeword: [],
                new_title_sel_index: 0,
                tags: [],
                button_text: [],
                creatives: [],
                newgroup: {
                    id: 0,
                    projectid: 0,
                    advertiser_id: 0,
                    campaign_name: '',
                    landing_type: 'LINK',
                    budget: '',
                    purpose: '1',
                },
                newgroupRules: {
                    campaign_name: [{
                            required: true,
                            message: '请输入广告组名称',
                            trigger: 'blur'
                        },
                        {
                            min: 1,
                            max: 100,
                            message: '长度在 1 到 100 个字符',
                            trigger: 'blur'
                        }
                    ],
                    budget: [{
                        validator: validateNumber,
                        trigger: 'blur'
                    }]
                },
                newplan: {
                    id: 0,
                    id_project: 0,
                    id_account: 0,
                    id_campaign: 0,
                    wordpackage: '',
                    convert_id: '',
                    convert_name: '',
                    interest_action_mode: 'UNLIMITED',
                    PutTarget: 1,
                    PutContent: 1,
                    directLink: 1,
                    external_url: '', //'https://www.chengzijianzhan.com/tetris/page/6777150659591405575',
                    id_direct_packet: '', // 本地定向包ID
                    id_creative: [],
                    media_nums: '',
                    title_nums: '',
                    button_text: '',
                    direct_action_scene: ['E-COMMERCE'],
                    direct_action_days: 7,
                    direct_action_categories: [],
                    direct_action_words: [],
                    direct_interest_categories: [],
                    direct_interest_words: [],
                    action_categories: [],
                    action_words: [],
                    interest_categories: [],
                    interest_words: [],
                    cpa_bid: 0,
                    deep_cpabid: 0,
                    urlinfo: {
                        id: 0,
                        thumbnail: '',
                        name: ''
                    },
                    new_title: [
                      {
                        title: '',
                        ids: '',
                      }
                    ],
                },
                targetshow: false,
                landshow: false,
                Cytitleshow:false,
                featureCur: 1,
                crowdCur: 1,
                prologicCur: 1,
                newplanRules: {
                    id_direct_packet: [{
                        required: true,
                        message: '请选择定向包',
                        trigger: 'blur'
                    }, ],
                    external_url: [{
                            required: true,
                            message: '请输入链接',
                            trigger: 'blur'
                        },
                        {
                            min: 2,
                            max: 200,
                            message: '长度在 2 到 200 个字符',
                            trigger: 'blur'
                        }
                    ],
                    convert_id: [{
                        required: true,
                        message: '请选择转换目标',
                        trigger: 'blur'
                    }, ],
                    button_text: [{
                        required: true,
                        message: '请选择行动号召',
                        trigger: 'blur'
                    }, ],
                    id_creative: [{
                        required: true,
                        message: '请选择创意包',
                        trigger: 'blur'
                    }, ],
                    media_nums: [{
                            required: true,
                            message: '请选择素材数量',
                            trigger: 'blur'
                        },
                        {
                            validator: validateMedia,
                            trigger: 'blur'
                        }
                    ],
                }
            }
        },
        computed: {
            actionObj: {
                get: function () {
                    let data = {
                        advertiser_id: this.advertiser_id,
                        scene: this.newplan.direct_action_scene,
                        days: this.newplan.direct_action_days,
                        categories: this.newplan.direct_action_categories,
                        words: this.newplan.direct_action_words,
                        targeting_type: 'ACTION', // ACTION（行为）、INTEREST（兴趣）
                    }
                    return data
                },
                set: function (v) {
                    // console.log('parent actionObj', v)
                    // 设置到数据上
                    this.newplan.direct_action_scene = v.scene
                    this.newplan.direct_action_days = v.days
                    this.newplan.direct_action_categories = v.categories
                    this.newplan.direct_action_words = v.words
                }
            },
            interestObj: {
                get: function () {
                    return {
                        advertiser_id: this.advertiser_id,
                        scene: this.newplan.direct_action_scene,
                        days: this.newplan.direct_action_days,
                        categories: this.newplan.direct_interest_categories,
                        words: this.newplan.direct_interest_words,
                        targeting_type: 'INTEREST', // ACTION（行为）、INTEREST（兴趣）
                    }
                },
                set: function (v) {
                    console.log('set interestObj', v)
                    this.newplan.direct_interest_categories = v.categories
                    this.newplan.direct_interest_words = v.words
                }
            },
            cpa_bid: {
                get: function () {
                    return {}
                },
                set: function (v) {
                    this.newplan.convert_id = v.convert_id
                    this.newplan.deep_cpabid = v.convert_deep_id
                    this.newplan.convert_name = v.convert_name
                }
            }
        },
        created() {
            this.projectId = this.$router.currentRoute.params.id
            this.accountId = this.$router.currentRoute.params.aid
            this.advertiser_id = this.$router.currentRoute.params.advid
            let groupId = this.$router.currentRoute.params.bid
            if (groupId > 0) {
                this.newgroup.id = groupId
                this.title = '修改广告组'
                this.titlePlan = '修改广告计划'
            }
        },
        mounted() {
            this.landing_types = landing_types
            this.loadData()
        },
        methods: {
            loadData() {
                this.fullScreenLoading = true
                this.$axios.get('/project/detail', {
                        projectid: this.projectId
                    })
                    .then(e => {
                        this.projectDetail = e.data
                    })
                // 定向包
                // this.loadDirectionalList({})
                let param = {}
                param['number'] = 100 //this.pageSize
                param['projectid'] = this.projectId
                this.$axios.get('/directional/list', param)
                    .then(e => {
                        this.directionaldata = e.data.items
                        // this.total = e.data.total
                        console.log('定向包', e.data)
                        // 创意包
                        this.$axios.get('/creative/list', {
                                id: this.projectId,
                                advertiser_id: this.advertiser_id
                            })
                            .then(e => {
                                // console.log(e)
                                this.creatives = e.data.items

                                // 创意词包查询
                                this.$axios.get('/creativeword', {
                                        id: this.projectId,
                                        advertiser_id: this.advertiser_id
                                    })
                                    .then(e => {
                                        this.creativeword = e.data.creative_word
                                        // console.log('this.creativeword', this.creativeword)
                                        // 行动号召
                                        this.$axios.get('/actiontext', {
                                                id: this.projectId,
                                                advertiser_id: this.advertiser_id
                                            })
                                            .then(e => {
                                                // console.log(e)
                                                this.button_text = e.data
                                                if (this.newgroup.id > 0) {
                                                    // 详情
                                                    this.loadGroupDetail()
                                                } else {
                                                    this.fullScreenLoading = false
                                                }
                                          })
                                    })

                            })
                    })

            },
            loadGroupDetail() {
                this.$axios.get('/adgroup/detail', {
                        id: this.newgroup.id,
                        advertiser_id: this.advertiser_id
                    })
                    .then(e => {
                        this.newgroup = parseObject(this.newgroup, e.data)
                        console.log('this.newgroup', this.newgroup)
                        this.fullScreenLoading = false
                    })
            },
            // loadDirectionalList(param) {
            //     param['number'] = 100 //this.pageSize
            //     param['projectid'] = this.projectId
            //     this.$axios.get('/directional/list', param)
            //         .then(e => {
            //             this.directionaldata = e.data.items
            //             // this.total = e.data.total
            //             console.log('定向包', e.data)
            //         })
            // },
            change() {
                this.$refs['newgroup'].validate((valid) => {
                    if (valid) {
                        this.newgroup.projectid = this.projectId
                        this.newgroup.advertiser_id = this.advertiser_id
                        this.loading = true
                        this.$axios.post('/adgroup/save', this.newgroup)
                            .then((e) => {
                                if (e.data.id) {
                                    this.newplan.id_campaign = e.data.id
                                    this.newplan.id_project = this.projectId
                                    this.newplan.id_account = this.accountId
                                    // 取得广告计划
                                    this.$axios.get('/adgroup/plan/detail', {
                                            id_campaign: this.newplan.id_campaign
                                        })
                                        .then(e => {
                                            this.loading = false
                                            if (e.data && JSON.stringify(e.data) != "{}") {

                                                this.newplan = parseObject(this.newplan, e.data)
                                                if (this.newplan.action_categories) {
                                                    this.newplan.direct_action_categories = this.newplan
                                                        .action_categories
                                                }
                                                if (this.newplan.action_words) {
                                                    this.newplan.direct_action_words = this.newplan
                                                        .action_words
                                                }
                                                if (this.newplan.interest_categories) {
                                                    this.newplan.direct_interest_categories = this
                                                        .newplan.interest_categories
                                                }
                                                if (this.newplan.interest_words) {
                                                    this.newplan.direct_interest_words = this.newplan
                                                        .interest_words
                                                }
                                                if (this.newplan.id_creative && this.newplan.id_creative
                                                    .length > 0) {
                                                    let tmp = []
                                                    this.newplan.id_creative.forEach((id, index) => {
                                                        let creativeId = parseInt(id)
                                                        if (this.creatives.findIndex(el => el
                                                                .id == creativeId) == -1) {
                                                            // 此创意包已经删除了，添加上去
                                                            let title = e.data.creative_title[
                                                                index]
                                                            this.creatives.push({
                                                                id: creativeId,
                                                                creative_name: '[已删除] ' +
                                                                    title
                                                            })
                                                        }
                                                        tmp.push(creativeId)
                                                    })
                                                    this.newplan.id_creative = tmp
                                                }
                                                if (this.newplan.new_title.length == 0) {
                                                  this.addNewTitle()
                                                }
                                                console.log(this.creatives)
                                                console.log('remote newplan', e.data, this.newplan)
                                            }
                                            this.show1 = false
                                            this.show2 = true
                                        }).catch(() => {
                                            this.loading = false
                                        })
                                } else {
                                    this.$message({
                                        type: 'error',
                                        message: '返回参数错误,没有ID!'
                                    })
                                }
                            }).catch(() => {
                                this.loading = false
                            })
                    } else {
                        console.log('error submit!!')
                        return false
                    }
                })
            },
            savePlan() {
                this.loading = true
                let postData = JSON.parse(JSON.stringify(this.newplan))
                if (this.crowdCur == 1) {
                    // 不自定义人群
                } else if (this.tags.length > 1) {
                    if (this.prologicCur == 1) {
                        postData['direct_retargeting_tags'] = this.tags[0]
                    } else if (this.prologicCur == 2) {
                        postData['direct_retargeting_tags_exclude'] = this.tags[0]
                    } else {
                        postData['direct_retargeting_tags'] = this.tags[0]
                        postData['direct_retargeting_tags_exclude'] = this.tags[1]
                    }
                }
                // 针对词包的处理
                postData.new_title.forEach((e, index) => {
                    let ids = this.matchId(e.title).join(',')
                    postData.new_title[index].ids = ids 
                })
                delete this.newplan.PutContent
                delete this.newplan.PutTarget
                delete this.newplan.directLink
                console.log('postData', postData)
                this.$refs['newplan'].validate((valid) => {
                    if (valid) {
                        this.$axios.post('/adgroup/plan/save', postData)
                            .then((e) => {
                                this.loading = false
                                this.$message({
                                    type: 'success',
                                    message: e.msg ? e.msg : '保存成功!'
                                })
                                // 跳转 grouplist/1/1
                                this.$router.replace({
                                    path: '/grouplist/' + this.projectId + '/' + this.accountId +
                                        '/' + this.advertiser_id
                                })
                            }).catch(() => {
                                this.loading = false
                            })
                    } else {
                        console.log('error submit!!')
                        this.loading = false
                        return false
                    }
                })
            },
            changeLogic(i) {
                this.prologicCur = i
                this.tags = []
            },
            back() {
                this.$router.go(-1)
            },
            landdchange() {
                this.landshow = true
            },
            targetchange() {
                if (this.newplan.external_url != '') {
                    this.targetshow = true
                } else {
                    this.$message.info('请先输入落地页链接')
                }
            },
            urlchangs(item) {
                // console.log('item', item)
                if (item.type == 'chengzi') {
                    this.newplan.external_url = 'https://www.chengzijianzhan.com/tetris/page/' + item.id
                } else {
                    this.newplan.external_url = item.url
                }
                this.newplan.urlinfo = item;
            },
            addNewTitle() {
              this.newplan.new_title.push({title:'', ids: ''})
            },
            deleteWord(item, index) {
              this.newplan.new_title.splice(index, 1)
            },
            insertWord(item, index) {
              // console.log(item, index)
              if (index == -1) {
                  index = this.new_title_sel_index
                  this.Cytitleshow = false
              }
              if (this.matchId(this.newplan.new_title[index].title).length >= 2) {
                this.$alert('最多插入两个词包', '提示', {
                  confirmButtonText: '确定',
                  callback: () => {
                    }
                  })
                return
              }
              // this.$refs.new_title[0].$refs.input.selectionStart
              item = item.name
              var elInput =  this.$refs.new_title[index].$refs.input// 根据id选择器选中对象
              var startPos = elInput.selectionStart// input 第0个字符到选中的字符
              var endPos = elInput.selectionEnd// 选中的字符到最后的字符
              if (startPos === undefined || endPos === undefined) return
              var txt = elInput.value
              // 将表情添加到选中的光标位置
              var result = txt.substring(0, startPos) + '{' + item + '}' + txt.substring(endPos)
              // elInput.value = result// 赋值给input的value
              this.newplan.new_title[index].title = result
              // 重新定义光标位置
              elInput.focus()
              elInput.selectionStart = startPos + item.length
              elInput.selectionEnd = startPos + item.length
              // this.form.message = result// 赋值给表单中的的字段
              // this.newplan.new_title[index].title = this.newplan.new_title[index].title + '{' + item.name + '}'
              // this.newplan.new_title[index].ids.push(item.id)
            },
            Cytitlechange(index){
                this.new_title_sel_index = index
                this.Cytitleshow = true
            },
            matchId(str) {
                var keys=[];
                var arr = str.match(/\{(.*?)\}/g);
                for(var key in arr){
                    var s=arr[key].replace("{","").replace("}","");
                    keys.push(s);
                }
                // 遍历查找
                let ret = []
                keys.forEach(k => {
                    let obj = this.creativeword.find(e => e.name == k)
                    if (obj) {
                        ret.push(obj.creative_word_id)
                    }
                })
                return ret
            }
        }
    }
</script>
